<?php
/*
 * @Date: 2021-09-20 12:14:54
 * @LastEditTime: 2022-05-29 13:11:02
 * @Description: 后台api接口
 * @FilePath: \contest\back\action.php
 */
require("../core/ExaminService.php");
require("../core/AdminService.php");
require("../models/ResultModel.class.php");
require("../models/AccessModel.class.php");

use core\AdminService;
use core\ExaminService;
use models\ResultModel;
use models\AccessModel;

session_start();

if (isset($_GET["a"])) {
    AdminService::initialize();
    ExaminService::initialize();
}



if (!isset($_SESSION['access'])) {
    ResultModel::Fail("请先登录");
}

global $access;
$access = unserialize($_SESSION['access']);
$level = $access->type;
if ($level < 2) {
    ResultModel::NoAuthority();
}

$action = $_GET["a"];
switch ($action) {
    case "login": // 登录
        login();
        break;
    case "logout": // 登出
        logout();
        break;
    case "export":  // 导出excel
        // export();
        export_excel();
        break;
    case "papera": // 添加试卷和修改试卷
        add_paper();
        break;
    case "paperd": // 删除试卷
        del_paper();
        break;
    case "paperg": // 获取试卷
        get_paper();
        break;
    case "pg": // 获取试卷列表
        get_papers();
        break;
    case "assign": // 获取试卷
        assign_paper();
        break;
    case "peopleg": // 获取用户数据
        isset($_GET['id']) ? get_single_people() :  get_peoples();
        break;
    case "peoplea": // 添加用户数据
        add_people();
        break;
    case "peopled": // 删除用户数据
        del_peoples();
        break;
    case "peopleu": // 修改用户数据
        upd_people();
        break;
    case "quesg": // 获取问题
        get_ques();
        break;
    case "quesa": // 添加问题
        add_ques();
        break;
    case "quesu": // 修改问题
        update_ques();
        break;
    case "quesd": // 删除问题
        delete_ques();
        break;
    default:
        die("错误请求！");
}

#region 用户登录、登出
/**
 * 登录
 */
function login()
{
    session_start();
    if (!isset($_POST['name']) || !isset($_POST['pwd'])) {
        ResultModel::Fail("参数校验失败！");
    }

    $account = $_POST['name'];
    $password = $_POST['pwd'];
    $result = ExaminService::Login($account, $password, 3);
    if ($result != null) {
        $amode = new AccessModel(3, $result[0][0], $account);
        // 保存用户信息
        $_SESSION['access'] = serialize($amode);

        ResultModel::Ok("登录成功！");
    }

    if (isset($type)) {
        ResultModel::Fail("管理员账号或密码错误！");
    } else {
        ResultModel::Fail("学号或密码错误！");
    }
}

/**
 * @description: 退出登录
 * @param {*} $url
 */
function logout($url = 'login.html')
{
    session_unset();
    session_destroy();
    ResultModel::Ok();
}
#endregion


#region subject 试卷的增删改查

/**
 * @description: 分配试卷给学生
 * @param {*}
 * @return {*}
 */
function assign_paper()
{
    if (!isset($_GET['pid']) || !isset($_GET['no'])) {
        ResultModel::Fail("错误请求");
    }

    $pid = $_GET['pid'];
    $no = $_GET['no'];

    $no_ary = explode(",", $no);
    foreach ($no_ary as $key => $value) {
        $num = AdminService::AssignPaper($pid, $value);
    }

    ResultModel::Ok();
}


/**
 * @description: 获取试卷
 * @param {*}
 * @return {*}
 */
function get_paper()
{
    if (isset($_GET['pid'])) {
        $pid  = $_GET['pid'];
        $result = AdminService::GetSinglePaper($pid)[0];
        $result['qs'] = AdminService::GetQuesArray($pid);
        ResultModel::Ok("", $result);
    } // 单试卷
    else {
        // 搜索条件
        $paras = !isset($_GET['searchParams']) ? null : json_decode($_GET['searchParams']);
        $page = isset($_GET['page']) ? $_GET['page'] : 1;
        $limit = isset($_GET['limit']) ? $_GET['limit'] : 10;

        $result = AdminService::GetPapers($page, $limit, $paras);
        $count = count($result);
        include_once('../utils/JsonUtil.php');
        include_once('../models/TableModel.class.php');
        utils\JsonResponse(new models\TableModel(0, '', $count, $result));
    } // 多题目搜索    
}

function get_papers()
{
    $sql = "select a.id,concat( a.id,' ', a.title) title from test_paper a order by createDate desc";
    $result = AdminService::$db->execute_dql_assoc($sql);
    ResultModel::Ok("", $result);
}

/**
 * @description: 添加试卷
 * @param {*}
 * @return {*}
 */
function add_paper()
{
    if (!isset($_POST['t']) || !isset($_POST['m']) || !isset($_POST['ids'])) {
        ResultModel::Fail("参数错误");
    }

    $title = $_POST['t'];
    $minutes = $_POST['m'];
    $ids = $_POST['ids'];

    if (strlen($title) < 1 || strlen($minutes) < 1 || strlen($ids) < 1) {
        ResultModel::Fail("参数错误");
    }

    // TODO 登录账号id
    global $access;
    $aid = $access->id;

    //试卷id集合
    $id_ary = explode(',', $ids);

    $paper_id = isset($_POST['id']) ? $_POST['id'] : "";
    if (strlen($paper_id) > 0) {
        $pid = $_POST['id'];

        AdminService::UpdatePaper($pid, $title, $minutes, 100);

        $list = AdminService::GetQuesArray($pid);
        $ques = AdminService::GetQuess();

        // 过滤确定题目是否真实存在
        for ($i = 0; $i < count($id_ary); $i++) {
            $qid = $id_ary[$i];

            if (strlen($qid) < 1 || !in_array($qid, $ques)) {
                array_splice($id_ary, $i, 1);
                AdminService::DelQuesFromPaper($pid, $qid);
            }
        }

        // 看看新题目是否存在老试卷里,不存在就添加,
        for ($i = 0; $i < count($id_ary); $i++) {
            $qid = $id_ary[$i];

            if (strlen($qid) > 0 && !in_array($qid, $list)) {
                AdminService::AddQuesToPaper($pid, $qid);
            }
        }

        // 看看老题目是否在新试卷里,不存在就删除,
        for ($i = 0; $i < count($list); $i++) {
            $qid = $list[$i];

            if (strlen($qid) > 0 && !in_array($qid, $id_ary)) {
                AdminService::DelQuesFromPaper($pid, $qid);
            }
        }
        ResultModel::Ok("修改成功");
    } // 如果存在id的话就是修改
    else {
        // 添加试卷
        $pid = AdminService::AddPaper($title, $aid, $minutes, 100);

        if (count($id_ary, 0) < 1) {
            ResultModel::Fail("请选择至少一个题目");
        }
        // 遍历添加题目到试卷
        foreach ($id_ary as $qid) {
            AdminService::AddQuesToPaper($pid, $qid);
        }

        ResultModel::Ok("添加成功");
    }
}

/**
 * @description: 删除试卷
 * @param {*}
 * @return {*}
 */
function del_paper()
{
    $pid = $_GET['pid'];

    if (!is_numeric($pid) || $pid < 1) {
        ResultModel::Fail("错误请求");
    }

    ExaminService::DelPaper($pid);
    ExaminService::DelQuesFromPaper($pid);

    ResultModel::Ok("删除成功");
}

#endregion


#region ques 问题

/**
 * @description: 或是题目
 * @param {*}
 * @return {*}
 */
function get_ques()
{
    // 获取问题试题信息
    if (isset($_GET["id"])) {
        $id = $_GET["id"];
        $question = AdminService::GetQuestion($id);
        ResultModel::Ok("", $data = $question[0]);
    }

    // 分页获取试题
    $paras = null;
    if (isset($_GET['searchParams'])) {
        $paras = json_decode($_GET['searchParams']);
    }

    $page = isset($_GET['page']) ? $_GET['page'] : 1;
    $limit = isset($_GET['limit']) ? $_GET['limit'] : 10;
    $arr = AdminService::GetQuestions($page, $limit, $paras);
    $result = $arr[0];
    $count = $arr[1];
    include_once('../utils/JsonUtil.php');
    include_once('../models/TableModel.class.php');
    utils\JsonResponse(new models\TableModel(0, '', $count, $result));
}

/**
 * @description: 添加题目
 * @param {*}
 * @return {*}
 */
function add_ques()
{
    $arys = array("question" => $_POST['t'], "type" => $_POST['type'], "answer" => $_POST['ans'], "A" => $_POST['a'], "B" => $_POST['b'], "C" => $_POST['c'], "D" => $_POST['d']);

    $accountId = 1;
    $result = AdminService::AddQuestion($arys, $accountId);
    ResultModel::Ok($result);
}

/**
 * @description: 修改题目
 * @param {*}
 * @return {*}
 */
function update_ques()
{
    $id = $_POST['id'];
    if (!isset($_POST['id']) || trim(strval($_POST['id'])) === "") {
        ResultModel::Fail("不存在这样的题目");
    }
    $arys = array("question" => $_POST['t'], "type" => $_POST['type'], "answer" => $_POST['ans'], "A" => $_POST['a'], "B" => $_POST['b'], "C" => $_POST['c'], "D" => $_POST['d']);

    global $access;
    $aid = $access->id;
    $result = AdminService::UpdateQuestion($arys, $id, $aid);
    ResultModel::Ok($result);
}

/**
 * @description: 删除题目
 * @param {*}
 * @return {*}
 */
function delete_ques()
{
    if (!isset($_GET['ids'])) {
        ResultModel::Fail("操作失败");
    }

    $ids = explode(',', $_GET['ids']);
    $ids = array_unique($ids);
    foreach ($ids as $key => $value) {
        if ($value == null && trim($value) == '') continue;
        AdminService::DeleteQuestion($value);
    }
    ResultModel::Ok();
}

#endregion


#region people 人员

/**
 * @description: 添加人员
 * @param {*}
 * @return {*}
 */
function add_people()
{
    if (!isset($_POST['no'])) ResultModel::Fail("参数错误");
    $type = 1;
    $condition = '';
    if ($_GET['t'] === 'student') {
        $type = 1;
        $condition = "no=" . $_POST['no'] . " and level = " . $type;
    } else if ($_GET['t'] === 'teacher') {
        $type = 2;
        if (!isset($_POST['p'])) ResultModel::Fail("参数错误");
        $condition = "no=" . $_POST['no'] . " or " . "phone=" . $_POST['p'] . " and level = " . $type;
    } else {
        ResultModel::Fail("错误请求");
    }

    // 检查是否存在此人员
    $objs = AdminService::SelectTable("people_account", "*", $condition);
    if ($objs != null && count($objs) >= 1) {
        if ($_POST['no'] === $objs[0]['no']) {
            ResultModel::Fail("已存在编号");
        } else if ($_POST['p'] === $objs[0]['phone']) {
            ResultModel::Fail('已存在此手机号');
        }
    } else {
        $arys = array("no" => $_POST['no'], "name" => $_POST['n'], "password" => '123456', "gender" => $_POST['sex'], "phone" => $_POST['p'], "email" => $_POST['e'], "remarks" => $_POST['r']);
        $result = AdminService::AddPeople($arys, $type);
        $result > 0 ? ResultModel::Ok() : ResultModel::Fail("添加失败！");
    }
}

/**
 * @description: 获取人员数量
 * @return {TableModel}
 */
function get_peoples()
{
    // 搜索条件
    $paras = !isset($_GET['searchParams']) ? null : json_decode($_GET['searchParams']);

    // 分页信息
    $page = !isset($_GET['page']) ? 1 : intval($_GET['page']);
    $limit = !isset($_GET['limit']) ? 15 : intval($_GET['limit']);

    $type = isset($_GET['t']) ||  $_GET['t'] === 'teacher' ? 2 : 1;
    $result = AdminService::GetPeoples($page, $limit, $type, $paras);
    $count = count($result);
    include_once('../utils/JsonUtil.php');
    include_once('../models/TableModel.class.php');
    utils\JsonResponse(new models\TableModel(0, '', $count, $result));
}

function get_single_people()
{
    if (!isset($_GET['id'])) ResultModel::Fail("参数错误");

    $result = AdminService::GetSinglePeople($_GET['id']);
    ResultModel::Ok("", $result);
}

/**
 * @description: 删除用户信息
 * @param {*}
 * @return {*}
 */
function del_peoples()
{
    if (!isset($_GET['ids'])) {
        ResultModel::Fail("操作失败");
    }

    $type = isset($_GET['t']) ||  $_GET['t'] === 'teacher' ? 2 : 1;
    $ids = explode(',', $_GET['ids']);
    $ids = array_unique($ids);
    foreach ($ids as $key => $value) {
        if ($value == null && trim($value) == '') continue;
        AdminService::DelPeople($value, $type);
    }

    ResultModel::Ok();
}

/**
 * @description: 修改用户信息
 * @param {*}
 * @return {*}
 */
function upd_people()
{
    $type = 0;
    if ($_GET['t'] === 'student') {
        $type = 1;
    } else if ($_GET['t'] === 'teacher') {
        $type = 2;
    } else {
        ResultModel::Fail("错误请求");
    }


    $ary = array("id" => $_POST['id'], "no" => $_POST['no'], "name" => $_POST['n'], "password" => '123456', "gender" => $_POST['sex'], "phone" => $_POST['p'], "email" => $_POST['e'], "remarks" => $_POST['r']);
    $result = AdminService::UpdatePeople($ary, $type);
    $result > 0 ? ResultModel::Ok() : ResultModel::Fail("添加失败！");
}
#endregion


// 学生成绩可以总结成Excel表导出来 - 教师、学生
function export_excel()
{
    AdminService::ExportExcel();
}

// TODO 
// bug
// NOTE
// FIXME
// INFO
// TAG
// XXX 
